const fs = require('fs');
const path = require('path');

// 上传文件分片
const uploadChunk = (req, res) => {
    const { fileName, chunkIndex, totalChunks } = req.body;
    const chunkFilePath = path.resolve(__dirname, '..', 'uploads', `${fileName}.part${chunkIndex}`);
    // 创建文件
    req.on('data', (chunk) => {
        fs.appendFileSync(chunkFilePath, chunk);
    });
    // 处理文件上传完成
    req.on('end', () => {
        if (parseInt(chunkIndex) + 1 === parseInt(totalChunks)) {
            mergeChunks(fileName, totalChunks, res);
        } else {
            res.status(200).json({ message: `接受切片 ${chunkIndex} of ${totalChunks}` });
        }
    });
    // 处理错误
    req.on('error', (error) => {
        res.status(500).json({ error: '文件上传失败', details: error });
    });
};

// 合并文件分片
const mergeChunks = (fileName, totalChunks, res) => {
    // 创建文件路径
    const filePath = path.resolve(__dirname, '..', 'uploads', fileName);
    // 创建写入流
    const writeStream = fs.createWriteStream(filePath);
    // 遍历分片文件，写入文件
    const appendChunk = (index) => {
        if (index >= totalChunks) {
            // 所有分片已写入，结束写入流
            writeStream.end();
            // 返回成功响应
            res.status(200).json({ message: '文件上传成功' });
            return;
        }
        // 创建读取流
        const chunkFilePath = path.resolve(__dirname, '..', 'uploads', `${fileName}.part${index}`);
        const readStream = fs.createReadStream(chunkFilePath);
        // 将分片写入文件
        readStream.pipe(writeStream, { end: false });
        readStream.on('end', () => {
            fs.unlinkSync(chunkFilePath); // 删除切片文件
            appendChunk(index + 1);
        });
        // 处理错误
        readStream.on('error', (error) => {
            res.status(500).json({ error: `文件切片合并失败 ${index}`, details: error });
            writeStream.close();
        });
    };

    appendChunk(0);
};

module.exports = {
    uploadChunk
};
